import { defineStore } from 'pinia'
import {
  getToken,
  setToken,
  removeToken,
  removeRefreshToken,
} from '@/utils/auth'
import { decodeToken, isTokenExpired } from '@/utils/jwtUtils'
import { login, logout, refreshToken, getUserInfo } from '@/api/user'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken() || '',
    userInfo: null || JSON.parse(localStorage.getItem('userInfo')),
    role: '',
  }),

  getters: {
    isLoggedIn: (state) => !!state.token && !isTokenExpired(state.token),
    userRole: (state) => state.role,
  },

  actions: {
    // 设置 Token
    setToken(token) {
      this.token = token
      setToken(token)
    },

    // 登录
    async login(loginData) {
      try {
        const data = await login(loginData)

        this.setToken(data.data)

        // 返回角色信息，让组件处理路由跳转
        return Promise.resolve({
          success: true,
          role: this.role,
        })
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 获取用户信息
    async getUserinfo() {
      // 从 localStorage 获取当前角色，确保与登录选择的角色一致
      const currentRole = localStorage.getItem('role') || this.role
      const userType = currentRole === 'student' ? 1 : 2

      const response = await getUserInfo(Number(userType))
      if (!response || !response.data) {
        throw new Error('获取用户信息失败：返回数据为空')
      }
      const { data } = response
      this.userInfo = data
      // 将用户信息存储到本地
      localStorage.setItem('userInfo', JSON.stringify(data))
      return data
    },

    // 登出
    async logOut() {
      await logout()
      this.resetState()
    },

    // 刷新 Token
    async refreshUserToken() {
      try {
        const { data } = await refreshToken()
        this.setToken(data.token)
        return data.token
      } catch (error) {
        this.resetState()
        return Promise.reject(error)
      }
    },
    // 设置role
    setRole(role) {
      this.role = role
    },
    // 获取role
    getRole() {
      return this.role
    },
    // 重置状态
    resetState() {
      this.token = ''
      this.userInfo = null
      this.role = ''
      // 清除本地存储
      localStorage.removeItem('userInfo')
      removeToken()
      removeRefreshToken()
    },
  },
})
